Various live patches ported from REL1_4
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
7
8 /**
9 * Depends on the CacheManager
10 */
11 require_once( 'CacheManager.php' );
12
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
18
19 /** Number of times to re-try an operation in case of deadlock */
20 define( 'DEADLOCK_TRIES', 4 );
21 /** Minimum time to wait before retry, in microseconds */
22 define( 'DEADLOCK_DELAY_MIN', 500000 );
23 /** Maximum time to wait before retry */
24 define( 'DEADLOCK_DELAY_MAX', 1500000 );
25
26 /**
27 * Database abstraction object
28 * @package MediaWiki
29 */
30 class Database {
31
32 #------------------------------------------------------------------------------
33 # Variables
34 #------------------------------------------------------------------------------
35 /**#@+
36 * @access private
37 */
38 var $mLastQuery = '';
39
40 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
41 var $mOut, $mOpened = false;
42
43 var $mFailFunction;
44 var $mTablePrefix;
45 var $mFlags;
46 var $mTrxLevel = 0;
47 /**#@-*/
48
49 #------------------------------------------------------------------------------
50 # Accessors
51 #------------------------------------------------------------------------------
52 # These optionally set a variable and return the previous state
53
54 /**
55 * Fail function, takes a Database as a parameter
56 * Set to false for default, 1 for ignore errors
57 */
58 function failFunction( $function = NULL ) {
59 return wfSetVar( $this->mFailFunction, $function );
60 }
61
62 /**
63 * Output page, used for reporting errors
64 * FALSE means discard output
65 */
66 function &setOutputPage( &$out ) {
67 $this->mOut =& $out;
68 }
69
70 /**
71 * Boolean, controls output of large amounts of debug information
72 */
73 function debug( $debug = NULL ) {
74 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
75 }
76
77 /**
78 * Turns buffering of SQL result sets on (true) or off (false).
79 * Default is "on" and it should not be changed without good reasons.
80 */
81 function bufferResults( $buffer = NULL ) {
82 if ( is_null( $buffer ) ) {
83 return !(bool)( $this->mFlags & DBO_NOBUFFER );
84 } else {
85 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
86 }
87 }
88
89 /**
90 * Turns on (false) or off (true) the automatic generation and sending
91 * of a "we're sorry, but there has been a database error" page on
92 * database errors. Default is on (false). When turned off, the
93 * code should use wfLastErrno() and wfLastError() to handle the
94 * situation as appropriate.
95 */
96 function ignoreErrors( $ignoreErrors = NULL ) {
97 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
98 }
99
100 /**
101 * The current depth of nested transactions
102 * @param integer $level
103 */
104 function trxLevel( $level = NULL ) {
105 return wfSetVar( $this->mTrxLevel, $level );
106 }
107
108 /**#@+
109 * Get function
110 */
111 function lastQuery() { return $this->mLastQuery; }
112 function isOpen() { return $this->mOpened; }
113 /**#@-*/
114
115 #------------------------------------------------------------------------------
116 # Other functions
117 #------------------------------------------------------------------------------
118
119 /**#@+
120 * @param string $server database server host
121 * @param string $user database user name
122 * @param string $password database user password
123 * @param string $dbname database name
124 */
125
126 /**
127 * @param failFunction
128 * @param $flags
129 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
130 */
131 function Database( $server = false, $user = false, $password = false, $dbName = false,
132 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
133
134 global $wgOut, $wgDBprefix, $wgCommandLineMode;
135 # Can't get a reference if it hasn't been set yet
136 if ( !isset( $wgOut ) ) {
137 $wgOut = NULL;
138 }
139 $this->mOut =& $wgOut;
140
141 $this->mFailFunction = $failFunction;
142 $this->mFlags = $flags;
143
144 if ( $this->mFlags & DBO_DEFAULT ) {
145 if ( $wgCommandLineMode ) {
146 $this->mFlags &= ~DBO_TRX;
147 } else {
148 $this->mFlags |= DBO_TRX;
149 }
150 }
151
152 /*
153 // Faster read-only access
154 if ( wfReadOnly() ) {
155 $this->mFlags |= DBO_PERSISTENT;
156 $this->mFlags &= ~DBO_TRX;
157 }*/
158
159 /** Get the default table prefix*/
160 if ( $tablePrefix == 'get from global' ) {
161 $this->mTablePrefix = $wgDBprefix;
162 } else {
163 $this->mTablePrefix = $tablePrefix;
164 }
165
166 if ( $server ) {
167 $this->open( $server, $user, $password, $dbName );
168 }
169 }
170
171 /**
172 * @static
173 * @param failFunction
174 * @param $flags
175 */
176 function newFromParams( $server, $user, $password, $dbName,
177 $failFunction = false, $flags = 0 )
178 {
179 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
180 }
181
182 /**
183 * Usually aborts on failure
184 * If the failFunction is set to a non-zero integer, returns success
185 */
186 function open( $server, $user, $password, $dbName ) {
187 # Test for missing mysql.so
188 # First try to load it
189 if (!@extension_loaded('mysql')) {
190 @dl('mysql.so');
191 }
192
193 # Otherwise we get a suppressed fatal error, which is very hard to track down
194 if ( !function_exists( 'mysql_connect' ) ) {
195 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
196 }
197
198 $this->close();
199 $this->mServer = $server;
200 $this->mUser = $user;
201 $this->mPassword = $password;
202 $this->mDBname = $dbName;
203
204 $success = false;
205
206 if ( $this->mFlags & DBO_PERSISTENT ) {
207 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
208 } else {
209 @/**/$this->mConn = mysql_connect( $server, $user, $password );
210 }
211
212 if ( $dbName != '' ) {
213 if ( $this->mConn !== false ) {
214 $success = @/**/mysql_select_db( $dbName, $this->mConn );
215 if ( !$success ) {
216 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
217 }
218 } else {
219 wfDebug( "DB connection error\n" );
220 wfDebug( "Server: $server, User: $user, Password: " .
221 substr( $password, 0, 3 ) . "...\n" );
222 $success = false;
223 }
224 } else {
225 # Delay USE query
226 $success = !!$this->mConn;
227 }
228
229 if ( !$success ) {
230 $this->reportConnectionError();
231 $this->close();
232 }
233 $this->mOpened = $success;
234 return $success;
235 }
236 /**#@-*/
237
238 /**
239 * Closes a database connection.
240 * if it is open : commits any open transactions
241 *
242 * @return bool operation success. true if already closed.
243 */
244 function close()
245 {
246 $this->mOpened = false;
247 if ( $this->mConn ) {
248 if ( $this->trxLevel() ) {
249 $this->immediateCommit();
250 }
251 return mysql_close( $this->mConn );
252 } else {
253 return true;
254 }
255 }
256
257 /**
258 * @access private
259 * @param string $msg error message ?
260 * @todo parameter $msg is not used
261 */
262 function reportConnectionError( $msg = '') {
263 if ( $this->mFailFunction ) {
264 if ( !is_int( $this->mFailFunction ) ) {
265 $ff = $this->mFailFunction;
266 $ff( $this, mysql_error() );
267 }
268 } else {
269 wfEmergencyAbort( $this, mysql_error() );
270 }
271 }
272
273 /**
274 * Usually aborts on failure
275 * If errors are explicitly ignored, returns success
276 */
277 function query( $sql, $fname = '', $tempIgnore = false ) {
278 global $wgProfiling, $wgCommandLineMode;
279
280 if ( $wgProfiling ) {
281 # generalizeSQL will probably cut down the query to reasonable
282 # logging size most of the time. The substr is really just a sanity check.
283 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
284 wfProfileIn( $profName );
285 }
286
287 $this->mLastQuery = $sql;
288
289 # Add a comment for easy SHOW PROCESSLIST interpretation
290 if ( $fname ) {
291 $commentedSql = "/* $fname */ $sql";
292 } else {
293 $commentedSql = $sql;
294 }
295
296 # If DBO_TRX is set, start a transaction
297 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
298 $this->begin();
299 }
300
301 if ( $this->debug() ) {
302 $sqlx = substr( $sql, 0, 500 );
303 $sqlx = strtr($sqlx,"\t\n",' ');
304 wfDebug( "SQL: $sqlx\n" );
305 }
306
307 # Do the query and handle errors
308 $ret = $this->doQuery( $commentedSql );
309 if ( false === $ret ) {
310 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
311 }
312
313 if ( $wgProfiling ) {
314 wfProfileOut( $profName );
315 }
316 return $ret;
317 }
318
319 /**
320 * The DBMS-dependent part of query()
321 * @param string $sql SQL query.
322 */
323 function doQuery( $sql ) {
324 if( $this->bufferResults() ) {
325 $ret = mysql_query( $sql, $this->mConn );
326 } else {
327 $ret = mysql_unbuffered_query( $sql, $this->mConn );
328 }
329 return $ret;
330 }
331
332 /**
333 * @param $error
334 * @param $errno
335 * @param $sql
336 * @param string $fname
337 * @param bool $tempIgnore
338 */
339 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
340 global $wgCommandLineMode, $wgFullyInitialised;
341 # Ignore errors during error handling to avoid infinite recursion
342 $ignore = $this->ignoreErrors( true );
343
344 if( $ignore || $tempIgnore ) {
345 wfDebug("SQL ERROR (ignored): " . $error . "\n");
346 } else {
347 $sql1line = str_replace( "\n", "\\n", $sql );
348 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
349 wfDebug("SQL ERROR: " . $error . "\n");
350 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
351 $message = "A database error has occurred\n" .
352 "Query: $sql\n" .
353 "Function: $fname\n" .
354 "Error: $errno $error\n";
355 if ( !$wgCommandLineMode ) {
356 $message = nl2br( $message );
357 }
358 wfDebugDieBacktrace( $message );
359 } else {
360 // this calls wfAbruptExit()
361 $this->mOut->databaseError( $fname, $sql, $error, $errno );
362 }
363 }
364 $this->ignoreErrors( $ignore );
365 }
366
367
368 /**
369 * Intended to be compatible with the PEAR::DB wrapper functions.
370 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
371 *
372 * ? = scalar value, quoted as necessary
373 * ! = raw SQL bit (a function for instance)
374 * & = filename; reads the file and inserts as a blob
375 * (we don't use this though...)
376 */
377 function prepare( $sql, $func = 'Database::prepare' ) {
378 /* MySQL doesn't support prepared statements (yet), so just
379 pack up the query for reference. We'll manually replace
380 the bits later. */
381 return array( 'query' => $sql, 'func' => $func );
382 }
383
384 function freePrepared( $prepared ) {
385 /* No-op for MySQL */
386 }
387
388 /**
389 * Execute a prepared query with the various arguments
390 * @param string $prepared the prepared sql
391 * @param mixed $args Either an array here, or put scalars as varargs
392 */
393 function execute( $prepared, $args = null ) {
394 if( !is_array( $args ) ) {
395 # Pull the var args
396 $args = func_get_args();
397 array_shift( $args );
398 }
399 $sql = $this->fillPrepared( $prepared['query'], $args );
400 return $this->query( $sql, $prepared['func'] );
401 }
402
403 /**
404 * Prepare & execute an SQL statement, quoting and inserting arguments
405 * in the appropriate places.
406 * @param string $query
407 * @param string $args (default null)
408 */
409 function safeQuery( $query, $args = null ) {
410 $prepared = $this->prepare( $query, 'Database::safeQuery' );
411 if( !is_array( $args ) ) {
412 # Pull the var args
413 $args = func_get_args();
414 array_shift( $args );
415 }
416 $retval = $this->execute( $prepared, $args );
417 $this->freePrepared( $prepared );
418 return $retval;
419 }
420
421 /**
422 * For faking prepared SQL statements on DBs that don't support
423 * it directly.
424 * @param string $preparedSql - a 'preparable' SQL statement
425 * @param array $args - array of arguments to fill it with
426 * @return string executable SQL
427 */
428 function fillPrepared( $preparedQuery, $args ) {
429 $n = 0;
430 reset( $args );
431 $this->preparedArgs =& $args;
432 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
433 array( &$this, 'fillPreparedArg' ), $preparedQuery );
434 }
435
436 /**
437 * preg_callback func for fillPrepared()
438 * The arguments should be in $this->preparedArgs and must not be touched
439 * while we're doing this.
440 *
441 * @param array $matches
442 * @return string
443 * @access private
444 */
445 function fillPreparedArg( $matches ) {
446 switch( $matches[1] ) {
447 case '\\?': return '?';
448 case '\\!': return '!';
449 case '\\&': return '&';
450 }
451 list( $n, $arg ) = each( $this->preparedArgs );
452 switch( $matches[1] ) {
453 case '?': return $this->addQuotes( $arg );
454 case '!': return $arg;
455 case '&':
456 # return $this->addQuotes( file_get_contents( $arg ) );
457 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
458 default:
459 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
460 }
461 }
462
463 /**#@+
464 * @param mixed $res A SQL result
465 */
466 /**
467 * Free a result object
468 */
469 function freeResult( $res ) {
470 if ( !@/**/mysql_free_result( $res ) ) {
471 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
472 }
473 }
474
475 /**
476 * Fetch the next row from the given result object, in object form
477 */
478 function fetchObject( $res ) {
479 @/**/$row = mysql_fetch_object( $res );
480 if( mysql_errno() ) {
481 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
482 }
483 return $row;
484 }
485
486 /**
487 * Fetch the next row from the given result object
488 * Returns an array
489 */
490 function fetchRow( $res ) {
491 @/**/$row = mysql_fetch_array( $res );
492 if (mysql_errno() ) {
493 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
494 }
495 return $row;
496 }
497
498 /**
499 * Get the number of rows in a result object
500 */
501 function numRows( $res ) {
502 @/**/$n = mysql_num_rows( $res );
503 if( mysql_errno() ) {
504 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
505 }
506 return $n;
507 }
508
509 /**
510 * Get the number of fields in a result object
511 * See documentation for mysql_num_fields()
512 */
513 function numFields( $res ) { return mysql_num_fields( $res ); }
514
515 /**
516 * Get a field name in a result object
517 * See documentation for mysql_field_name()
518 */
519 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
520
521 /**
522 * Get the inserted value of an auto-increment row
523 *
524 * The value inserted should be fetched from nextSequenceValue()
525 *
526 * Example:
527 * $id = $dbw->nextSequenceValue('page_page_id_seq');
528 * $dbw->insert('page',array('page_id' => $id));
529 * $id = $dbw->insertId();
530 */
531 function insertId() { return mysql_insert_id( $this->mConn ); }
532
533 /**
534 * Change the position of the cursor in a result object
535 * See mysql_data_seek()
536 */
537 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
538
539 /**
540 * Get the last error number
541 * See mysql_errno()
542 */
543 function lastErrno() {
544 if ( $this->mConn ) {
545 return mysql_errno( $this->mConn );
546 } else {
547 return mysql_errno();
548 }
549 }
550
551 /**
552 * Get a description of the last error
553 * See mysql_error() for more details
554 */
555 function lastError() {
556 if ( $this->mConn ) {
557 $error = mysql_error( $this->mConn );
558 } else {
559 $error = mysql_error();
560 }
561 if( $error ) {
562 $error .= ' (' . $this->mServer . ')';
563 }
564 return $error;
565 }
566 /**
567 * Get the number of rows affected by the last write query
568 * See mysql_affected_rows() for more details
569 */
570 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
571 /**#@-*/ // end of template : @param $result
572
573 /**
574 * Simple UPDATE wrapper
575 * Usually aborts on failure
576 * If errors are explicitly ignored, returns success
577 *
578 * This function exists for historical reasons, Database::update() has a more standard
579 * calling convention and feature set
580 */
581 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
582 {
583 $table = $this->tableName( $table );
584 $sql = "UPDATE $table SET $var = '" .
585 $this->strencode( $value ) . "' WHERE ($cond)";
586 return !!$this->query( $sql, DB_MASTER, $fname );
587 }
588
589 /**
590 * Simple SELECT wrapper, returns a single field, input must be encoded
591 * Usually aborts on failure
592 * If errors are explicitly ignored, returns FALSE on failure
593 */
594 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
595 if ( !is_array( $options ) ) {
596 $options = array( $options );
597 }
598 $options['LIMIT'] = 1;
599
600 $res = $this->select( $table, $var, $cond, $fname, $options );
601 if ( $res === false || !$this->numRows( $res ) ) {
602 return false;
603 }
604 $row = $this->fetchRow( $res );
605 if ( $row !== false ) {
606 $this->freeResult( $res );
607 return $row[0];
608 } else {
609 return false;
610 }
611 }
612
613 /**
614 * Returns an optional USE INDEX clause to go after the table, and a
615 * string to go at the end of the query
616 */
617 function makeSelectOptions( $options ) {
618 if ( !is_array( $options ) ) {
619 $options = array( $options );
620 }
621
622 $tailOpts = '';
623
624 if ( isset( $options['ORDER BY'] ) ) {
625 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
626 }
627 if ( isset( $options['LIMIT'] ) ) {
628 $tailOpts .= " LIMIT {$options['LIMIT']}";
629 }
630
631 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
632 $tailOpts .= ' FOR UPDATE';
633 }
634
635 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
636 $tailOpts .= ' LOCK IN SHARE MODE';
637 }
638
639 if ( isset( $options['USE INDEX'] ) ) {
640 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
641 } else {
642 $useIndex = '';
643 }
644 return array( $useIndex, $tailOpts );
645 }
646
647 /**
648 * SELECT wrapper
649 */
650 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
651 {
652 if( is_array( $vars ) ) {
653 $vars = implode( ',', $vars );
654 }
655 if( is_array( $table ) ) {
656 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
657 } elseif ($table!='') {
658 $from = ' FROM ' .$this->tableName( $table );
659 } else {
660 $from = '';
661 }
662
663 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
664
665 if( !empty( $conds ) ) {
666 if ( is_array( $conds ) ) {
667 $conds = $this->makeList( $conds, LIST_AND );
668 }
669 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
670 } else {
671 $sql = "SELECT $vars $from $useIndex $tailOpts";
672 }
673 return $this->query( $sql, $fname );
674 }
675
676 /**
677 * Single row SELECT wrapper
678 * Aborts or returns FALSE on error
679 *
680 * $vars: the selected variables
681 * $conds: a condition map, terms are ANDed together.
682 * Items with numeric keys are taken to be literal conditions
683 * Takes an array of selected variables, and a condition map, which is ANDed
684 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
685 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
686 * $obj- >page_id is the ID of the Astronomy article
687 *
688 * @todo migrate documentation to phpdocumentor format
689 */
690 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
691 $options['LIMIT'] = 1;
692 $res = $this->select( $table, $vars, $conds, $fname, $options );
693 if ( $res === false || !$this->numRows( $res ) ) {
694 return false;
695 }
696 $obj = $this->fetchObject( $res );
697 $this->freeResult( $res );
698 return $obj;
699
700 }
701
702 /**
703 * Removes most variables from an SQL query and replaces them with X or N for numbers.
704 * It's only slightly flawed. Don't use for anything important.
705 *
706 * @param string $sql A SQL Query
707 * @static
708 */
709 function generalizeSQL( $sql ) {
710 # This does the same as the regexp below would do, but in such a way
711 # as to avoid crashing php on some large strings.
712 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
713
714 $sql = str_replace ( "\\\\", '', $sql);
715 $sql = str_replace ( "\\'", '', $sql);
716 $sql = str_replace ( "\\\"", '', $sql);
717 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
718 $sql = preg_replace ('/".*"/s', "'X'", $sql);
719
720 # All newlines, tabs, etc replaced by single space
721 $sql = preg_replace ( "/\s+/", ' ', $sql);
722
723 # All numbers => N
724 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
725
726 return $sql;
727 }
728
729 /**
730 * Determines whether a field exists in a table
731 * Usually aborts on failure
732 * If errors are explicitly ignored, returns NULL on failure
733 */
734 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
735 $table = $this->tableName( $table );
736 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
737 if ( !$res ) {
738 return NULL;
739 }
740
741 $found = false;
742
743 while ( $row = $this->fetchObject( $res ) ) {
744 if ( $row->Field == $field ) {
745 $found = true;
746 break;
747 }
748 }
749 return $found;
750 }
751
752 /**
753 * Determines whether an index exists
754 * Usually aborts on failure
755 * If errors are explicitly ignored, returns NULL on failure
756 */
757 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
758 $info = $this->indexInfo( $table, $index, $fname );
759 if ( is_null( $info ) ) {
760 return NULL;
761 } else {
762 return $info !== false;
763 }
764 }
765
766
767 /**
768 * Get information about an index into an object
769 * Returns false if the index does not exist
770 */
771 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
772 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
773 # SHOW INDEX should work for 3.x and up:
774 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
775 $table = $this->tableName( $table );
776 $sql = 'SHOW INDEX FROM '.$table;
777 $res = $this->query( $sql, $fname );
778 if ( !$res ) {
779 return NULL;
780 }
781
782 while ( $row = $this->fetchObject( $res ) ) {
783 if ( $row->Key_name == $index ) {
784 return $row;
785 }
786 }
787 return false;
788 }
789
790 /**
791 * Query whether a given table exists
792 */
793 function tableExists( $table ) {
794 $table = $this->tableName( $table );
795 $old = $this->ignoreErrors( true );
796 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
797 $this->ignoreErrors( $old );
798 if( $res ) {
799 $this->freeResult( $res );
800 return true;
801 } else {
802 return false;
803 }
804 }
805
806 /**
807 * mysql_fetch_field() wrapper
808 * Returns false if the field doesn't exist
809 *
810 * @param $table
811 * @param $field
812 */
813 function fieldInfo( $table, $field ) {
814 $table = $this->tableName( $table );
815 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
816 $n = mysql_num_fields( $res );
817 for( $i = 0; $i < $n; $i++ ) {
818 $meta = mysql_fetch_field( $res, $i );
819 if( $field == $meta->name ) {
820 return $meta;
821 }
822 }
823 return false;
824 }
825
826 /**
827 * mysql_field_type() wrapper
828 */
829 function fieldType( $res, $index ) {
830 return mysql_field_type( $res, $index );
831 }
832
833 /**
834 * Determines if a given index is unique
835 */
836 function indexUnique( $table, $index ) {
837 $indexInfo = $this->indexInfo( $table, $index );
838 if ( !$indexInfo ) {
839 return NULL;
840 }
841 return !$indexInfo->Non_unique;
842 }
843
844 /**
845 * INSERT wrapper, inserts an array into a table
846 *
847 * $a may be a single associative array, or an array of these with numeric keys, for
848 * multi-row insert.
849 *
850 * Usually aborts on failure
851 * If errors are explicitly ignored, returns success
852 */
853 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
854 # No rows to insert, easy just return now
855 if ( !count( $a ) ) {
856 return true;
857 }
858
859 $table = $this->tableName( $table );
860 if ( !is_array( $options ) ) {
861 $options = array( $options );
862 }
863 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
864 $multi = true;
865 $keys = array_keys( $a[0] );
866 } else {
867 $multi = false;
868 $keys = array_keys( $a );
869 }
870
871 $sql = 'INSERT ' . implode( ' ', $options ) .
872 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
873
874 if ( $multi ) {
875 $first = true;
876 foreach ( $a as $row ) {
877 if ( $first ) {
878 $first = false;
879 } else {
880 $sql .= ',';
881 }
882 $sql .= '(' . $this->makeList( $row ) . ')';
883 }
884 } else {
885 $sql .= '(' . $this->makeList( $a ) . ')';
886 }
887 return !!$this->query( $sql, $fname );
888 }
889
890 /**
891 * UPDATE wrapper, takes a condition array and a SET array
892 */
893 function update( $table, $values, $conds, $fname = 'Database::update' ) {
894 $table = $this->tableName( $table );
895 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
896 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
897 $this->query( $sql, $fname );
898 }
899
900 /**
901 * Makes a wfStrencoded list from an array
902 * $mode: LIST_COMMA - comma separated, no field names
903 * LIST_AND - ANDed WHERE clause (without the WHERE)
904 * LIST_SET - comma separated with field names, like a SET clause
905 * LIST_NAMES - comma separated field names
906 */
907 function makeList( $a, $mode = LIST_COMMA ) {
908 if ( !is_array( $a ) ) {
909 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
910 }
911
912 $first = true;
913 $list = '';
914 foreach ( $a as $field => $value ) {
915 if ( !$first ) {
916 if ( $mode == LIST_AND ) {
917 $list .= ' AND ';
918 } else {
919 $list .= ',';
920 }
921 } else {
922 $first = false;
923 }
924 if ( $mode == LIST_AND && is_numeric( $field ) ) {
925 $list .= "($value)";
926 } elseif ( $mode == LIST_AND && is_array ($value) ) {
927 $list .= $field." IN (".$this->makeList($value).") ";
928 } else {
929 if ( $mode == LIST_AND || $mode == LIST_SET ) {
930 $list .= $field.'=';
931 }
932 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
933 }
934 }
935 return $list;
936 }
937
938 /**
939 * Change the current database
940 */
941 function selectDB( $db ) {
942 $this->mDBname = $db;
943 return mysql_select_db( $db, $this->mConn );
944 }
945
946 /**
947 * Starts a timer which will kill the DB thread after $timeout seconds
948 */
949 function startTimer( $timeout ) {
950 global $IP;
951 if( function_exists( 'mysql_thread_id' ) ) {
952 # This will kill the query if it's still running after $timeout seconds.
953 $tid = mysql_thread_id( $this->mConn );
954 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
955 }
956 }
957
958 /**
959 * Stop a timer started by startTimer()
960 * Currently unimplemented.
961 *
962 */
963 function stopTimer() { }
964
965 /**
966 * Format a table name ready for use in constructing an SQL query
967 *
968 * This does two important things: it quotes table names which as necessary,
969 * and it adds a table prefix if there is one.
970 *
971 * All functions of this object which require a table name call this function
972 * themselves. Pass the canonical name to such functions. This is only needed
973 * when calling query() directly.
974 *
975 * @param string $name database table name
976 */
977 function tableName( $name ) {
978 global $wgSharedDB;
979 # Skip quoted literals
980 if ( $name{0} != '`' ) {
981 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
982 $name = "{$this->mTablePrefix}$name";
983 }
984 if ( isset( $wgSharedDB ) && 'user' == $name ) {
985 $name = "`$wgSharedDB`.`$name`";
986 } else {
987 # Standard quoting
988 $name = "`$name`";
989 }
990 }
991 return $name;
992 }
993
994 /**
995 * Fetch a number of table names into an array
996 * This is handy when you need to construct SQL for joins
997 *
998 * Example:
999 * extract($dbr->tableNames('user','watchlist'));
1000 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1001 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1002 */
1003 function tableNames() {
1004 $inArray = func_get_args();
1005 $retVal = array();
1006 foreach ( $inArray as $name ) {
1007 $retVal[$name] = $this->tableName( $name );
1008 }
1009 return $retVal;
1010 }
1011
1012 /**
1013 * Wrapper for addslashes()
1014 * @param string $s String to be slashed.
1015 * @return string slashed string.
1016 */
1017 function strencode( $s ) {
1018 return addslashes( $s );
1019 }
1020
1021 /**
1022 * If it's a string, adds quotes and backslashes
1023 * Otherwise returns as-is
1024 */
1025 function addQuotes( $s ) {
1026 if ( is_null( $s ) ) {
1027 $s = 'NULL';
1028 } else {
1029 # This will also quote numeric values. This should be harmless,
1030 # and protects against weird problems that occur when they really
1031 # _are_ strings such as article titles and string->number->string
1032 # conversion is not 1:1.
1033 $s = "'" . $this->strencode( $s ) . "'";
1034 }
1035 return $s;
1036 }
1037
1038 /**
1039 * Returns an appropriately quoted sequence value for inserting a new row.
1040 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1041 * subclass will return an integer, and save the value for insertId()
1042 */
1043 function nextSequenceValue( $seqName ) {
1044 return NULL;
1045 }
1046
1047 /**
1048 * USE INDEX clause
1049 * PostgreSQL doesn't have them and returns ""
1050 */
1051 function useIndexClause( $index ) {
1052 return 'USE INDEX ('.$index.')';
1053 }
1054
1055 /**
1056 * REPLACE query wrapper
1057 * PostgreSQL simulates this with a DELETE followed by INSERT
1058 * $row is the row to insert, an associative array
1059 * $uniqueIndexes is an array of indexes. Each element may be either a
1060 * field name or an array of field names
1061 *
1062 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1063 * However if you do this, you run the risk of encountering errors which wouldn't have
1064 * occurred in MySQL
1065 *
1066 * @todo migrate comment to phodocumentor format
1067 */
1068 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1069 $table = $this->tableName( $table );
1070
1071 # Single row case
1072 if ( !is_array( reset( $rows ) ) ) {
1073 $rows = array( $rows );
1074 }
1075
1076 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1077 $first = true;
1078 foreach ( $rows as $row ) {
1079 if ( $first ) {
1080 $first = false;
1081 } else {
1082 $sql .= ',';
1083 }
1084 $sql .= '(' . $this->makeList( $row ) . ')';
1085 }
1086 return $this->query( $sql, $fname );
1087 }
1088
1089 /**
1090 * DELETE where the condition is a join
1091 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1092 *
1093 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1094 * join condition matches, set $conds='*'
1095 *
1096 * DO NOT put the join condition in $conds
1097 *
1098 * @param string $delTable The table to delete from.
1099 * @param string $joinTable The other table.
1100 * @param string $delVar The variable to join on, in the first table.
1101 * @param string $joinVar The variable to join on, in the second table.
1102 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1103 */
1104 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1105 if ( !$conds ) {
1106 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1107 }
1108
1109 $delTable = $this->tableName( $delTable );
1110 $joinTable = $this->tableName( $joinTable );
1111 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1112 if ( $conds != '*' ) {
1113 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1114 }
1115
1116 return $this->query( $sql, $fname );
1117 }
1118
1119 /**
1120 * Returns the size of a text field, or -1 for "unlimited"
1121 */
1122 function textFieldSize( $table, $field ) {
1123 $table = $this->tableName( $table );
1124 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1125 $res = $this->query( $sql, 'Database::textFieldSize' );
1126 $row = $this->fetchObject( $res );
1127 $this->freeResult( $res );
1128
1129 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1130 $size = $m[1];
1131 } else {
1132 $size = -1;
1133 }
1134 return $size;
1135 }
1136
1137 /**
1138 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1139 */
1140 function lowPriorityOption() {
1141 return 'LOW_PRIORITY';
1142 }
1143
1144 /**
1145 * DELETE query wrapper
1146 *
1147 * Use $conds == "*" to delete all rows
1148 */
1149 function delete( $table, $conds, $fname = 'Database::delete' ) {
1150 if ( !$conds ) {
1151 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1152 }
1153 $table = $this->tableName( $table );
1154 $sql = "DELETE FROM $table ";
1155 if ( $conds != '*' ) {
1156 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1157 }
1158 return $this->query( $sql, $fname );
1159 }
1160
1161 /**
1162 * INSERT SELECT wrapper
1163 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1164 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1165 * $conds may be "*" to copy the whole table
1166 * srcTable may be an array of tables.
1167 */
1168 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1169 $destTable = $this->tableName( $destTable );
1170 if( is_array( $srcTable ) ) {
1171 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1172 } else {
1173 $srcTable = $this->tableName( $srcTable );
1174 }
1175 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1176 ' SELECT ' . implode( ',', $varMap ) .
1177 " FROM $srcTable";
1178 if ( $conds != '*' ) {
1179 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1180 }
1181 return $this->query( $sql, $fname );
1182 }
1183
1184 /**
1185 * Construct a LIMIT query with optional offset
1186 * This is used for query pages
1187 */
1188 function limitResult($limit,$offset) {
1189 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1190 }
1191
1192 /**
1193 * Returns an SQL expression for a simple conditional.
1194 * Uses IF on MySQL.
1195 *
1196 * @param string $cond SQL expression which will result in a boolean value
1197 * @param string $trueVal SQL expression to return if true
1198 * @param string $falseVal SQL expression to return if false
1199 * @return string SQL fragment
1200 */
1201 function conditional( $cond, $trueVal, $falseVal ) {
1202 return " IF($cond, $trueVal, $falseVal) ";
1203 }
1204
1205 /**
1206 * Determines if the last failure was due to a deadlock
1207 */
1208 function wasDeadlock() {
1209 return $this->lastErrno() == 1213;
1210 }
1211
1212 /**
1213 * Perform a deadlock-prone transaction.
1214 *
1215 * This function invokes a callback function to perform a set of write
1216 * queries. If a deadlock occurs during the processing, the transaction
1217 * will be rolled back and the callback function will be called again.
1218 *
1219 * Usage:
1220 * $dbw->deadlockLoop( callback, ... );
1221 *
1222 * Extra arguments are passed through to the specified callback function.
1223 *
1224 * Returns whatever the callback function returned on its successful,
1225 * iteration, or false on error, for example if the retry limit was
1226 * reached.
1227 */
1228 function deadlockLoop() {
1229 $myFname = 'Database::deadlockLoop';
1230
1231 $this->query( 'BEGIN', $myFname );
1232 $args = func_get_args();
1233 $function = array_shift( $args );
1234 $oldIgnore = $this->ignoreErrors( true );
1235 $tries = DEADLOCK_TRIES;
1236 if ( is_array( $function ) ) {
1237 $fname = $function[0];
1238 } else {
1239 $fname = $function;
1240 }
1241 do {
1242 $retVal = call_user_func_array( $function, $args );
1243 $error = $this->lastError();
1244 $errno = $this->lastErrno();
1245 $sql = $this->lastQuery();
1246
1247 if ( $errno ) {
1248 if ( $this->wasDeadlock() ) {
1249 # Retry
1250 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1251 } else {
1252 $this->reportQueryError( $error, $errno, $sql, $fname );
1253 }
1254 }
1255 } while( $this->wasDeadlock() && --$tries > 0 );
1256 $this->ignoreErrors( $oldIgnore );
1257 if ( $tries <= 0 ) {
1258 $this->query( 'ROLLBACK', $myFname );
1259 $this->reportQueryError( $error, $errno, $sql, $fname );
1260 return false;
1261 } else {
1262 $this->query( 'COMMIT', $myFname );
1263 return $retVal;
1264 }
1265 }
1266
1267 /**
1268 * Do a SELECT MASTER_POS_WAIT()
1269 *
1270 * @param string $file the binlog file
1271 * @param string $pos the binlog position
1272 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1273 */
1274 function masterPosWait( $file, $pos, $timeout ) {
1275 $fname = 'Database::masterPosWait';
1276 wfProfileIn( $fname );
1277
1278
1279 # Commit any open transactions
1280 $this->immediateCommit();
1281
1282 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1283 $encFile = $this->strencode( $file );
1284 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1285 $res = $this->doQuery( $sql );
1286 if ( $res && $row = $this->fetchRow( $res ) ) {
1287 $this->freeResult( $res );
1288 return $row[0];
1289 } else {
1290 return false;
1291 }
1292 }
1293
1294 /**
1295 * Get the position of the master from SHOW SLAVE STATUS
1296 */
1297 function getSlavePos() {
1298 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1299 $row = $this->fetchObject( $res );
1300 if ( $row ) {
1301 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1302 } else {
1303 return array( false, false );
1304 }
1305 }
1306
1307 /**
1308 * Get the position of the master from SHOW MASTER STATUS
1309 */
1310 function getMasterPos() {
1311 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1312 $row = $this->fetchObject( $res );
1313 if ( $row ) {
1314 return array( $row->File, $row->Position );
1315 } else {
1316 return array( false, false );
1317 }
1318 }
1319
1320 /**
1321 * Begin a transaction, or if a transaction has already started, continue it
1322 */
1323 function begin( $fname = 'Database::begin' ) {
1324 if ( !$this->mTrxLevel ) {
1325 $this->immediateBegin( $fname );
1326 } else {
1327 $this->mTrxLevel++;
1328 }
1329 }
1330
1331 /**
1332 * End a transaction, or decrement the nest level if transactions are nested
1333 */
1334 function commit( $fname = 'Database::commit' ) {
1335 if ( $this->mTrxLevel ) {
1336 $this->mTrxLevel--;
1337 }
1338 if ( !$this->mTrxLevel ) {
1339 $this->immediateCommit( $fname );
1340 }
1341 }
1342
1343 /**
1344 * Rollback a transaction
1345 */
1346 function rollback( $fname = 'Database::rollback' ) {
1347 $this->query( 'ROLLBACK', $fname );
1348 $this->mTrxLevel = 0;
1349 }
1350
1351 /**
1352 * Begin a transaction, committing any previously open transaction
1353 */
1354 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1355 $this->query( 'BEGIN', $fname );
1356 $this->mTrxLevel = 1;
1357 }
1358
1359 /**
1360 * Commit transaction, if one is open
1361 */
1362 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1363 $this->query( 'COMMIT', $fname );
1364 $this->mTrxLevel = 0;
1365 }
1366
1367 /**
1368 * Return MW-style timestamp used for MySQL schema
1369 */
1370 function timestamp( $ts=0 ) {
1371 return wfTimestamp(TS_MW,$ts);
1372 }
1373
1374 /**
1375 * @todo document
1376 */
1377 function &resultObject( &$result ) {
1378 if( empty( $result ) ) {
1379 return NULL;
1380 } else {
1381 return new ResultWrapper( $this, $result );
1382 }
1383 }
1384
1385 /**
1386 * Return aggregated value alias
1387 */
1388 function aggregateValue ($valuedata,$valuename='value') {
1389 return $valuename;
1390 }
1391
1392 /**
1393 * @return string wikitext of a link to the server software's web site
1394 */
1395 function getSoftwareLink() {
1396 return "[http://www.mysql.com/ MySQL]";
1397 }
1398
1399 /**
1400 * @return string Version information from the database
1401 */
1402 function getServerVersion() {
1403 return mysql_get_server_info();
1404 }
1405 }
1406
1407 /**
1408 * Database abstraction object for mySQL
1409 * Inherit all methods and properties of Database::Database()
1410 *
1411 * @package MediaWiki
1412 * @see Database
1413 */
1414 class DatabaseMysql extends Database {
1415 # Inherit all
1416 }
1417
1418
1419 /**
1420 * Result wrapper for grabbing data queried by someone else
1421 *
1422 * @package MediaWiki
1423 */
1424 class ResultWrapper {
1425 var $db, $result;
1426
1427 /**
1428 * @todo document
1429 */
1430 function ResultWrapper( $database, $result ) {
1431 $this->db =& $database;
1432 $this->result =& $result;
1433 }
1434
1435 /**
1436 * @todo document
1437 */
1438 function numRows() {
1439 return $this->db->numRows( $this->result );
1440 }
1441
1442 /**
1443 * @todo document
1444 */
1445 function &fetchObject() {
1446 return $this->db->fetchObject( $this->result );
1447 }
1448
1449 /**
1450 * @todo document
1451 */
1452 function &fetchRow() {
1453 return $this->db->fetchRow( $this->result );
1454 }
1455
1456 /**
1457 * @todo document
1458 */
1459 function free() {
1460 $this->db->freeResult( $this->result );
1461 unset( $this->result );
1462 unset( $this->db );
1463 }
1464
1465 function seek( $row ) {
1466 $this->db->dataSeek( $this->result, $row );
1467 }
1468 }
1469
1470 #------------------------------------------------------------------------------
1471 # Global functions
1472 #------------------------------------------------------------------------------
1473
1474 /**
1475 * Standard fail function, called by default when a connection cannot be
1476 * established.
1477 * Displays the file cache if possible
1478 */
1479 function wfEmergencyAbort( &$conn, $error ) {
1480 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1481 global $wgSitename, $wgServer;
1482
1483 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1484 # Hard coding strings instead.
1485
1486 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1487 $1';
1488 $mainpage = 'Main Page';
1489 $searchdisabled = <<<EOT
1490 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1491 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1492 EOT;
1493
1494 $googlesearch = "
1495 <!-- SiteSearch Google -->
1496 <FORM method=GET action=\"http://www.google.com/search\">
1497 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1498 <A HREF=\"http://www.google.com/\">
1499 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1500 border=\"0\" ALT=\"Google\"></A>
1501 </td>
1502 <td>
1503 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1504 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1505 <font size=-1>
1506 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
1507 <input type='hidden' name='ie' value='$2'>
1508 <input type='hidden' name='oe' value='$2'>
1509 </font>
1510 </td></tr></TABLE>
1511 </FORM>
1512 <!-- SiteSearch Google -->";
1513 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1514
1515
1516 if( !headers_sent() ) {
1517 header( 'HTTP/1.0 500 Internal Server Error' );
1518 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1519 /* Don't cache error pages! They cause no end of trouble... */
1520 header( 'Cache-control: none' );
1521 header( 'Pragma: nocache' );
1522 }
1523 $msg = wfGetSiteNotice();
1524 if($msg == '') {
1525 $msg = str_replace( '$1', $error, $noconnect );
1526 }
1527 $text = $msg;
1528
1529 if($wgUseFileCache) {
1530 if($wgTitle) {
1531 $t =& $wgTitle;
1532 } else {
1533 if($title) {
1534 $t = Title::newFromURL( $title );
1535 } elseif (@/**/$_REQUEST['search']) {
1536 $search = $_REQUEST['search'];
1537 echo $searchdisabled;
1538 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1539 $wgInputEncoding ), $googlesearch );
1540 wfErrorExit();
1541 } else {
1542 $t = Title::newFromText( $mainpage );
1543 }
1544 }
1545
1546 $cache = new CacheManager( $t );
1547 if( $cache->isFileCached() ) {
1548 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1549 $cachederror . "</b></p>\n";
1550
1551 $tag = '<div id="article">';
1552 $text = str_replace(
1553 $tag,
1554 $tag . $msg,
1555 $cache->fetchPageText() );
1556 }
1557 }
1558
1559 echo $text;
1560 wfErrorExit();
1561 }
1562
1563 ?>